#!/bin/bash

# Feng Admin 端口清理工具
# 用于清理可能被占用的端口

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Feng Admin - 端口清理工具${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 默认端口
BACKEND_PORT=5001
FRONTEND_PORT=5173

# 从配置文件读取端口
if [ -f "../apps/backend/.env" ]; then
    PORT=$(grep "^BACKEND_PORT=" ../apps/backend/.env | cut -d'=' -f2)
    BACKEND_PORT=${PORT:-5001}
fi

if [ -f "../apps/frontend/.env" ]; then
    PORT=$(grep "^VITE_SERVER_PORT=" ../apps/frontend/.env | cut -d'=' -f2)
    FRONTEND_PORT=${PORT:-5173}
fi

echo -e "${YELLOW}检查端口占用情况...${NC}"
echo ""

# 检查后端端口
echo -e "${BLUE}后端端口 ${BACKEND_PORT}:${NC}"
if lsof -ti:${BACKEND_PORT} &> /dev/null; then
    echo -e "${RED}✗ 端口被占用${NC}"
    echo "  占用进程:"
    lsof -i:${BACKEND_PORT} | grep LISTEN
    echo ""
    read -p "是否要清理此端口? (y/N): " clean_backend
    if [[ $clean_backend =~ ^[Yy]$ ]]; then
        lsof -ti:${BACKEND_PORT} | xargs kill -9 2>/dev/null
        echo -e "${GREEN}✓ 后端端口已清理${NC}"
    else
        echo -e "${YELLOW}跳过后端端口清理${NC}"
    fi
else
    echo -e "${GREEN}✓ 端口可用${NC}"
fi

echo ""

# 检查前端端口
echo -e "${BLUE}前端端口 ${FRONTEND_PORT}:${NC}"
if lsof -ti:${FRONTEND_PORT} &> /dev/null; then
    echo -e "${RED}✗ 端口被占用${NC}"
    echo "  占用进程:"
    lsof -i:${FRONTEND_PORT} | grep LISTEN
    echo ""
    read -p "是否要清理此端口? (y/N): " clean_frontend
    if [[ $clean_frontend =~ ^[Yy]$ ]]; then
        lsof -ti:${FRONTEND_PORT} | xargs kill -9 2>/dev/null
        echo -e "${GREEN}✓ 前端端口已清理${NC}"
    else
        echo -e "${YELLOW}跳过前端端口清理${NC}"
    fi
else
    echo -e "${GREEN}✓ 端口可用${NC}"
fi

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  端口检查完成${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""


